const url = require('url');
const got = require('@/utils/got');
const cheerio = require('cheerio');

function isComment(index, node) {
    return node.type === 'comment'
}

module.exports = async (ctx) => {
    let list = [];

    const today = new Date();
    const twoDigit = (num) => num < 10 ? '0'+num : ''+num;
    const dateStr = `${today.getFullYear()}${twoDigit(today.getMonth()+1)}/${twoDigit(today.getDate())}`;

    const root_url = 'https://epaper.huanbohainews.com.cn/tsldrb/pc/col/index.html';
    const nodeUrls = Object.keys([...new Array(3)]).map((k,i) =>
        `https://epaper.huanbohainews.com.cn/tsldrb/pc/col/${dateStr}/node_${i+1}.html`
    );

    const responses = await Promise.all(nodeUrls.map(url => got({
        method: 'get',
        url,
    })));

    responses.forEach(resp => {
        const $ = cheerio.load(resp.data);
        const lst = $('tr.wzlb_tr');
        for(let i=0; i<lst.length; i++) {
            const it = $(lst[i]);
            const title = it.find('a').first();
            list.push({
                title: title.text(),
                link: title.attr('href'),
            });
        }
    });

    const count = [];
    for (let i = 0; i < Math.min(list.length, 10); ++i) {
        count.push(i);
    }

    const items = await Promise.all(
        count.map((i) => {
            // const item = $(list[i]);
            // const title = item.find('a').first();
            // const link = title.attr('href');
            const item = list[i];
            // const title = item.title;
            // let link = `https://www.hebpta.com.cn:8090/door/article?id=${item.id}`;
            // if (item.jumpType) {

            // }

            const {link, title} = item;

            // const pubDate = new Date(item.find('.xxgk-line-comdate').text() + ' 00:00:00 GMT+8').toUTCString();
            const pubDate = new Date(`${today.getFullYear()}/${twoDigit(today.getMonth()+1)}/${twoDigit(today.getDate())}` + ' 00:00:00 GMT+8').toUTCString();

            return ctx.cache.tryGet('huanbohainews' + link, async () => {
                // const date = item.find('div.postSubtitle').text().trim();
                // const match = /(\d+\/\d+\/\d{4}\s+\d+:\d+:\d+\s*(?:AM|PM))/i.exec(date);
                // const pubDate = match && new Date(match[1] + ' GMT+8').toUTCString();

                const res = await got({ method: 'get',
                    url: url.resolve(nodeUrls[0], link)
                    // url: link
                });
                const content = cheerio.load(res.data);
                // const content = cheerio.load(`<div id="content">${(res.data.data || {}).articleContent || ''}</div>`);
                const post = content('div.detail-art');
                post.find('#content').contents().filter(isComment).remove();

                post.find('img[data-src]').each((_, ele) => {
                    ele = content(ele);
                    ele.attr('src', ele.attr('data-src'));
                    // ele.attr('alt', title.text());
                    // ele.attr('title', title.text());
                    ele.removeAttr('class');
                    ele.removeAttr('data-src');
                });

                return {
                    // title: title.text(),
                    // title: title.attr('title'),
                    title,
                    link: url.resolve(nodeUrls[0], link),
                    pubDate,
                    description: post.html(),
                };
            });
        })
    );

    ctx.state.data = {
        title: '唐山劳动日报-要闻',
        link: root_url,
        item: items,
    };
};
